package com.laundry.service;

import com.laundry.entity.LaundryOrder;
import com.laundry.entity.User;
import com.laundry.repository.LaundryOrderRepository;
import com.laundry.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class DashboardService {
    
    private final LaundryOrderRepository orderRepository;
    private final UserRepository userRepository;
    
    public Map<String, Object> getUserDashboard() {
        User user = getCurrentUser();
        
        Map<String, Object> dashboard = new HashMap<>();
        
        // 订单统计
        Map<String, Object> orderStats = new HashMap<>();
        orderStats.put("total", orderRepository.countByUser(user));
        orderStats.put("pending", orderRepository.countByUserAndStatus(user, LaundryOrder.OrderStatus.PENDING));
        orderStats.put("processing", orderRepository.countByUserAndStatus(user, LaundryOrder.OrderStatus.PROCESSING));
        orderStats.put("completed", orderRepository.countByUserAndStatus(user, LaundryOrder.OrderStatus.COMPLETED));
        orderStats.put("cancelled", orderRepository.countByUserAndStatus(user, LaundryOrder.OrderStatus.CANCELLED));
        
        dashboard.put("orderStats", orderStats);
        
        // 最近订单
        List<LaundryOrder> recentOrders = orderRepository.findByUser(user, 
                org.springframework.data.domain.PageRequest.of(0, 5, 
                org.springframework.data.domain.Sort.by("createdAt").descending())).getContent();
        dashboard.put("recentOrders", recentOrders);
        
        // 用户信息
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", user.getUsername());
        userInfo.put("nickname", user.getNickname());
        userInfo.put("avatar", user.getAvatar());
        userInfo.put("memberSince", user.getCreatedAt());
        userInfo.put("emailVerified", user.getEmailVerified());
        userInfo.put("mobileVerified", user.getMobileVerified());
        userInfo.put("realNameVerified", user.getRealNameVerified());
        
        dashboard.put("userInfo", userInfo);
        
        // 本月统计
        LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).truncatedTo(ChronoUnit.DAYS);
        LocalDateTime monthEnd = monthStart.plusMonths(1);
        
        List<LaundryOrder> monthlyOrders = orderRepository.findByCreatedAtBetween(monthStart, monthEnd);
        
        Map<String, Object> monthlyStats = new HashMap<>();
        monthlyStats.put("orderCount", monthlyOrders.size());
        
        BigDecimal monthlySpent = monthlyOrders.stream()
                .filter(order -> order.getPaymentStatus() == LaundryOrder.PaymentStatus.PAID)
                .map(LaundryOrder::getFinalAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        monthlyStats.put("totalSpent", monthlySpent);
        
        dashboard.put("monthlyStats", monthlyStats);
        
        return dashboard;
    }
    
    public Map<String, Object> getOrderStats() {
        User user = getCurrentUser();
        
        Map<String, Object> stats = new HashMap<>();
        
        // 按状态统计
        for (LaundryOrder.OrderStatus status : LaundryOrder.OrderStatus.values()) {
            Long count = orderRepository.countByUserAndStatus(user, status);
            stats.put(status.name().toLowerCase(), count);
        }
        
        // 总计
        stats.put("total", orderRepository.countByUser(user));
        
        return stats;
    }
    
    private User getCurrentUser() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return userRepository.findByUsernameOrEmailOrMobile(username, username, username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }
}
